/* eslint-disable react-hooks/exhaustive-deps */
/**
 * @description 跟踪参数配置树
 * @author gf
 */
import React, {
  Fragment,
  memo,
  useCallback,
  useEffect,
  useMemo,
  useState,
} from "react";
import styles from "./TreeParams.less";
import { Select, Tree, TreeSelect } from "antd";
import icon_file_open from "@/assets/icons/icon-report-file.png";
import icon_file from "@/assets/icons/icon-file.png";

import icon_arrow from "@/assets/icons/icon-arrow.png";
import icon_tree_expended from "@/assets/icons/icon-tree-expand.png";
// import '@/mock/SigFundParams'
import {
  queryFundTree,
  queryFundEventConfigList,
  queryFundEventConfig,
} from "@/pages/SigFundParams/service";
import {
  queryPortfolioEventConfigList,
  queryPortfolioList,
  queryPortfolioEventConfig,
} from "@/pages/ComParams/service";
import cn from "classnames";
import * as _ from "lodash";

interface TreeSearchTProps {
  onClick: (e: any) => void;
  treeId?: number | string; // id
  record?: string; //secuCode
  isIndicator?: boolean; // 指标支持反选，指标支持一级选择
  fundCode: string; // 基金组合代码
  paramsType: "sig" | "com"; // sig 各基， com：组合
  portfolioCodeProp?: string; // 组合列表跳转到组合参数配置
  nodeInfo?: any; // 更改开关并且提交成功后，更改树节点
}

const TreeParams = (props: TreeSearchTProps) => {
  const { onClick, paramsType, portfolioCodeProp, nodeInfo } = props;

  const [treeSelect, setTreeSelect] = useState([]);
  const [searchVal, setSearchVal] = useState("");
  const [treeSelectVal, setTreeSelectVal] = useState("");
  const [tree, setTree] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([] as string[]);
  const [checkedKeys, setCheckedKeys] = useState([] as string[]);
  const [portfolioCode, setPortfolioCode] = useState("");
  const [portfolioList, setPortfolioList] = useState([]);

  useEffect(() => {
    // console.log(paramsType)

    const _resolveSelect = (data: any[]) => {
      const arr = [];
      data.map((v) => {
        if (v.children) {
          arr.push({
            key: v.key,
            title: v.title,
            fundType: v.fundType,
            value: v.key,
            disabled: !v.parentName,
            children: _resolveSelect(v.children),
          });
        } else {
          arr.push({
            key: v.key,
            title: v.title,
            value: v.key,
            disabled: !v.parentName,
            fundType: v.fundType,
          });
        }
      });
      return arr;
    };
    if (paramsType === "sig") {
      queryFundTree({
        type: "wind基金分类",
      }).then((res) => {
        if (res?.code === "0") {
          setTreeSelect(_resolveSelect(res?.data));
          if (!_.isEmpty(res.data)) {
            setTreeSelectVal(
              `${res?.data[0].children[0].title}_${res?.data[0].children[0].id}`
            );
          }
        }
      });
    } else {
      queryPortfolioList().then((res) => {
        if (res?.code === "0") {
          if (portfolioCodeProp) {
            setPortfolioCode(portfolioCodeProp);
          } else {
            setPortfolioCode(res?.data[0].portfolioCode);
          }
          setPortfolioList(res?.data);
        }
      });
    }
  }, [portfolioCodeProp]);

  useEffect(() => {
    const _resolveEventData = (data: any[]) => {
      // groupName, eventName
      const a = _.groupBy(data, "groupName");
      // console.log(a);
      const arr = [];

      // 处理三级
      const third = (secData) => {
        const d = _.groupBy(secData, "eventName");
        // console.log(d);
        let t = [];
        for (let key of Object.keys(d)) {
          console.log(d[key]);
          if (d[key].length > 1 || d[key][0].eventCodeName) {
            t = t.concat([{ title: key, children: d[key],parentCode: d[key][0].eventParentCode}]);
          } else {
            t = t.concat(d[key]);
          }
        }
        return t;
      };

      for (let key of Object.keys(a)) {
        arr.push({
          title: key,
          key,
          level: 1,
          children: third(a[key]).map((v) => {
            console.log(v);
            
            if (v.title) {
              return {
                title: v.title,
                key: v.title,
                level: 2,
                value: v.parentCode,
                children: v.children.map((m) => {
                  return {
                    title: m.eventCodeName,
                    key: m.id,
                    value: m.eventCode,
                    label: m.eventCodeName,
                    preValue: m.preValue,
                    level: 3,
                    parentKey: v.title,
                    eventHeader: m.eventHeader,
                    enable: m.enable,
                  };
                }),
              };
            } else {
              return {
                title: v.eventName,
                key: v.id,
                value: v.eventCode,
                label: v.eventName,
                preValue: v.preValue,
                level: 2,
                parentKey: key,
                eventHeader: v.eventHeader,
                enable: v.enable,
              };
            }
          }),
        });
      }
      console.log(arr);

      setTree(arr);
      if (!_.isEmpty(arr)) {
        let o: any;
        if (arr[0].children[0]?.children) {
          o = arr[0].children[0]?.children[0]; // 三级
        } else {
          o = arr[0].children[0]; // 二级
        }
        o.fundType = paramsType;
        // onClick(o)
        setCheckedKeys([o.key]);
        setExpandedKeys(arr.map((a) => a.key));
      }
      return arr;
    };
    if (paramsType === "sig") {
      if (!treeSelectVal) return;
      const fundType = treeSelectVal.split("_")[1];
      queryFundEventConfigList({
        fundType,
      }).then((res) => {
        if (res?.code === "0") {
          _resolveEventData(res?.data);
        }
      });
    } else {
      if (!portfolioCode) return;
      queryPortfolioEventConfigList({ portfolioCode }).then((res) => {
        if (res?.code === "0") {
          _resolveEventData(res?.data);
        }
      });
    }
  }, [treeSelectVal, portfolioCode]);

  useEffect(() => {
    if (!_.isEmpty(nodeInfo)) {
      console.log(nodeInfo, tree);
      let flag = false;
      for (let i = 0; i < tree?.length; i++) {
        if (flag) break;
        tree[i]?.children?.forEach((node) => {
          if (node?.key === nodeInfo?.id) {
            node.enable = nodeInfo.enable;
            flag = true;
          } else if (node.children) {
            node.children.forEach((m) => {
              if (m.key === nodeInfo.id) {
                m.enable = nodeInfo.enable;
              }
            });
          }
        });
      }
      setTree(_.cloneDeep(tree));
    }
  }, [nodeInfo]);

  // 查询阈值单基
  const handleQuerySing = (params) => {
    queryFundEventConfig(params).then((res) => {
      if (res?.code === "0") {
        const {
          eventHeader,
          id,
          eventName,
          eventCode,
          preValue,
          enable,
          eventCodeName,
        } = res?.data;
        const obj = {
          eventHeader: eventHeader,
          fundType: "sig",
          key: id,
          label: eventCodeName || eventName,
          level: 2,
          preValue,
          title: eventCodeName || eventName,
          value: eventCode,
          enable,
        };
        onClick(obj);
      }
    });
  };

  // 查询阈值组合
  const handleQueryCom = (params) => {
    queryPortfolioEventConfig(params).then((res) => {
      if (res?.code === "0") {
        const { eventHeader, id, eventName, eventCode, preValue, enable, eventCodeName } =
          res?.data;
        const obj = {
          eventHeader: eventHeader,
          fundType: "com",
          key: id,
          label: eventCodeName || eventName,
          level: 2,
          preValue,
          title: eventCodeName || eventName,
          value: eventCode,
          enable,
        };
        onClick(obj);
      }
    });
  };

  useEffect(() => {
    console.log(checkedKeys);

    if (checkedKeys.length === 0) return;
    if (paramsType === "sig") {
      const fundType = treeSelectVal.split("_")[1];
      handleQuerySing({
        fundType,
        id: checkedKeys[0],
      });
    } else {
      handleQueryCom({
        portfolioCode,
        id: checkedKeys[0],
      });
    }
  }, [checkedKeys]);

  const handleClick = (a: any, e: any, exp?: string[]) => {
    // console.log(a, e)
    if (e.level === 1 || e.children) {
      handleClickIcon(a, e, true);
      return;
    }
    e.fundType = paramsType;
    // onClick(e)
    setCheckedKeys([e.key]);
  };

  const tilteRender = useCallback(
    (node: any) => {
      // console.log('titleRender');
      return node.level === 1 ? (
        <Fragment>
          {node.level === 1 && (
            <Fragment>
              <img
                className={cn(
                  styles.tree_arrow,
                  expandedKeys.includes(node.key) && styles.tree_arrow_open
                )}
                src={icon_tree_expended}
                alt="ex"
              />
              <img
                className={styles.tree_file}
                src={
                  expandedKeys.includes(node.key) ? icon_file_open : icon_file
                }
                alt="file"
              />
            </Fragment>
          )}
          <span
            onClick={(e: any) => {
              e.stopPropagation();
              handleClick(null, node);
            }}
            className={cn(
              styles.titleHover
              // node.level === 1 && styles.disabledTitle,
            )}
          >
            {node.title}
          </span>
        </Fragment>
      ) : node.level === 2 ? (
        <div className={styles.secTitle}>
          {node.children && !_.isEmpty(node.children) && (
            <img
              className={cn(
                styles.tree_arrow_second,
                expandedKeys.includes(node.key) && styles.tree_arrow_open
              )}
              src={icon_tree_expended}
              alt="ex"
            />
          )}
          <span
            onClick={(e: any) => {
              e.stopPropagation();
              handleClick(null, node);
            }}
            className={cn(styles.titleHover, styles.secondTitle)}
            title={node.label || node.title}
          >
            {node.title}
          </span>
          {(node.enable ||
            node?.children?.filter((v) => v.enable).length > 0) && (
            <span className="open" />
          )}
        </div>
      ) : node.level === 3 ? (
        <div className={cn(styles.secTitle, styles.thirdTitle)}>
          {/* {node.children && !_.isEmpty(node.children) && (
            <img className={styles.secondArrow} src={icon_arrow} alt="second" />
          )} */}
          <span
            onClick={(e: any) => {
              e.stopPropagation();
              handleClick(null, node);
            }}
            className={cn(styles.thirdTitle_hover, styles.secondTitle)}
            title={node.label || node.title}
          >
            <span>{node.title}</span>
          </span>
          {node.enable && <span className="open" />}
        </div>
      ) : null;
    },
    [searchVal, expandedKeys]
  );

  const handleChangeSelect = (e: string) => {
    setPortfolioCode(e);
  };

  const handleClickIcon = (a: any, e: any, isTitle?: boolean) => {
    const copyArr: string[] = _.cloneDeep(expandedKeys);
    const i: number = _.findIndex(copyArr, (k: string) => k === e.key);
    if (i === -1 && (a || isTitle)) {
      copyArr.push(e.key);
    } else if (a || isTitle) {
      copyArr.splice(i, 1);
    }
    setExpandedKeys(copyArr);
  };

  const handleChangeTreeSelect = (e) => {
    if (!e) {
      setTreeSelectVal("");
    } else {
      setTreeSelectVal(e);
    }
  };

  return (
    <div className={cn(styles.treeSearch, styles.treeSearchIndustry)}>
      {paramsType === "sig" && (
        <TreeSelect
          className={styles.treeSelect}
          suffixIcon={<img src={icon_arrow} alt="arrow" />}
          onChange={handleChangeTreeSelect}
          value={treeSelectVal}
          allowClear
          treeDefaultExpandAll={true}
          treeData={treeSelect}
          dropdownMatchSelectWidth={false}
        />
      )}
      {paramsType == "com" && (
        <Select
          suffixIcon={<img src={icon_arrow} alt="arrow" />}
          className={styles.cusSelect}
          onChange={handleChangeSelect}
          value={portfolioCode}
        >
          {portfolioList &&
            portfolioList?.map((v) => (
              <Select.Option key={v.portfolioCode} value={v.portfolioCode}>
                {v.portfolioName}
              </Select.Option>
            ))}
        </Select>
      )}

      <Tree
        titleRender={tilteRender}
        onClick={handleClickIcon}
        treeData={tree}
        expandedKeys={expandedKeys}
        selectedKeys={checkedKeys}
      />
    </div>
  );
};

export default TreeParams;
